import { useEffect, useRef, useCallback } from 'react';
import config from '../config';
import useImage from './useImage';
import usePosition from './usePosition';

const useCanvas = (selector = '#root', wrapperId = 'canvas') => {
  const [isLoading, imageMap] = useImage();
  const [, { getCollectionPositions }] = usePosition();
  const el = useRef(document.createElement('canvas'));
  const canvas = useRef(el.current.getContext('2d')!);

  // 初始化canvas
  useEffect(() => {
    const root = document.querySelector(selector)!;
    el.current.width = config.canvas.width;
    el.current.height = config.canvas.height;
    el.current.id = wrapperId;

    root.insertAdjacentElement('afterbegin', el.current);
  }, []);

  // 渲染模型
  const drawModel = useCallback(
    (type, count = 1) => {
      if (!isLoading) {
        getCollectionPositions(count).forEach(position => {
          console.log(type, count);

          const img = imageMap.get(type)!;
          canvas.current.drawImage(
            img,
            position.x,
            position.y,
            config.model.width,
            config.model.height,
          );
        });
      }
    },
    [isLoading],
  );

  return [{ el: el.current, canvas: canvas.current }, { drawModel }] as const;
};

export default useCanvas;
